<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>聊天</title>
</head>
<style type="text/css" media="screen">
    div {
        border: 1px solid #cccccc;
        width: 500px;
        min-height: 100px;
    }
</style>

<body>
    <table>
        <tr>
            <td style="width:60%">
                <div id="show">
                </div>
                <label id='lb_time'></label>
            </td>
            <td style="width:30%">
                <input type="text" id="message" name="" value="test" placeholder="">
                <input type="text" id="name" value="" placeholder="昵称;">
                <a href="javascript:void(0)" onclick="send()">发送</a>
                <a href="javascript:void(0)" onclick="exit()">退出</a>
            </td>
        </tr>
    </table>

    <!-- <input type="text" id="token" name="" value="" placeholder="" readonly="false"> -->
</body>
<script src="./jquery-3.2.1.min.js"></script>
<script type="text/javascript">  
    var ws = new WebSocket("ws://115.159.159.37:8181?t=test");
    ws.onopen = function () {
        console.log("连接状态", ws);
        $("#show").html("连接状态;" + ws.readyState + "</br>");
        console.log("open");
        ws.open("start");
    };
    ws.onmessage = function (evt) {
        if (evt.data.substring(0, 6) == '[time]') {
            $("#lb_time").text(evt.data)
        }
        else {
            $("#show").append(evt.data + "</br>");
        }
    };
    ws.onclose = function (evt) {
        console.log("WebSocketClosed!");
        console.log(evt);
    };
    ws.onerror = function (evt) {
        console.log("WebSocketError!");
    };

    function send() {
        var msg = $("#message").val();
        var key = $("#token").val();
        var name = $("#name").val();
        var str = `{"name":"${name}","msg":"${msg}"}`//,key:'${key}'
        console.log("发送", str);
        ws.send(str);
    };

    function exit() {
        var r = ws.close();
        console.log("退出", r);
    }  
</script>

</html>